//--------------------------------------------------------------------
// FileName: ImageConverter.cpp
// Author: zhuyf
// Version: 0.1
// Date: 2013.5.10
// Description: 使用 GDI+ 转换图片格式
//
// History:
// 1.Date:
//   Author:
//   Modification:
//
//--------------------------------------------------------------------
#include "StdAfx.h"
#include "ImageConverter.h"

using namespace Gdiplus;
#pragma comment(lib, "GdiPlus.lib")

CImageConverter::CImageConverter(void)
{
}

CImageConverter::~CImageConverter(void)
{
}

void CImageConverter::Init()
{
	GdiplusStartup(&token_, &input_, NULL);
}

void CImageConverter::Deinit()
{
	GdiplusShutdown(token_);
}

bool CImageConverter::BmpToPng(LPCWSTR szBmp, LPCWSTR szPng)
{
	CLSID encoderClsid;
	Image *pImage = Bitmap::FromFile(szBmp, TRUE);
	if (!GetEncoderClsid(_T("image/png"), &encoderClsid))
		return false;

	Status stat = pImage->Save(szPng, &encoderClsid, NULL);
	if (stat != Ok)
		return FALSE;

	delete pImage;
	pImage = NULL;

	return true;
}

bool CImageConverter::PngToBmp(LPCWSTR szPng, LPCWSTR szBmp)
{
	CLSID encoderClsid;
	Image *pImage = Bitmap::FromFile(szPng, TRUE);
	if (!GetEncoderClsid(_T("image/bmp"), &encoderClsid))
		return false;

	Status stat = pImage->Save(szBmp, &encoderClsid, NULL);
	if (stat != Ok)
		return false;

	delete pImage;
	pImage = NULL;

	return true;
}

bool CImageConverter::BmpToJpg(LPCWSTR szBmp, LPCWSTR szJpg)
{
	CLSID encoderClsid;
	Image *pImage = Bitmap::FromFile(szBmp, TRUE);
	if (!GetEncoderClsid(_T("image/jpeg"), &encoderClsid))
		return false;

	Status stat = pImage->Save(szJpg, &encoderClsid, NULL);
	if (stat != Ok)
		return false;

	delete pImage;
	pImage = NULL;

	return true;
}

bool CImageConverter::JpgToBmp(LPCWSTR szJpg, LPCWSTR szBmp)
{
	CLSID encoderClsid;
	Image *pImage = Bitmap::FromFile(szJpg, TRUE);
	if (!GetEncoderClsid(_T("image/bmp"), &encoderClsid))
		return false;

	Status stat = pImage->Save(szBmp, &encoderClsid, NULL);
	if (stat != Ok)
		return false;

	delete pImage;
	pImage = NULL;

	return true;
}

bool CImageConverter::GetEncoderClsid(TCHAR *pFormat, CLSID *pClsid)
{
	UINT numEncoders = 0,size = 0;
	ImageCodecInfo *pImageCodecInfo = NULL;

	GetImageEncodersSize(&numEncoders, &size);
	if (size == 0)
		return false;

	pImageCodecInfo = (ImageCodecInfo *)(malloc(size));
	if (pImageCodecInfo == NULL)
		return false;

	GetImageEncoders(numEncoders, size, pImageCodecInfo);

	bool bfound = false;
	for (UINT i = 0; !bfound && i < numEncoders;  i++)
	{
		if (_wcsicmp(pImageCodecInfo[i].MimeType, pFormat) == 0)
		{
			*pClsid = pImageCodecInfo[i].Clsid;
			bfound = true;
		}
	}

	free(pImageCodecInfo);

	return bfound;
}